package org.edu.modules.enroll.controller;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.*;

import org.edu.modules.enroll.vo.ApplyMngImportVo;
import org.edu.modules.enroll.vo.ExportApplyMngVo;
import org.edu.modules.enroll.vo.ScoreAnnouncementVo;
import org.edu.modules.enroll.vo.VeZsRegistrationVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:  报名信息管理业务控制
 * @Author:  wcj
 * @Date:  2021-04-20
 * @Version:  V2.0
 */

@Api(tags="报名信息管理")
@RestController
@RequestMapping("enroll/ApplyMsgMng")
@Slf4j
public class ApplyMsgMngController {

    @Resource
    private VeZsRegistrationService veZsRegistrationService;

    @Resource
    private VeDictQuarterService veDictQuarterService;

    @Resource
    private VeDictXueziService veDictXueziService;

    @Resource
    private VeDictAreaService veDictAreaService;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private ExportApplyMngService exportApplyMngService;

    @Resource
    private SysDictItemService sysDictItemService;

    @Resource
    private VeApplyMngImportService veApplyMngImportService;



        @ApiOperation(value = "获取报名信息管理集合")
        @PostMapping(value = "/applyMsgList")
        public Result<?> getApplyMsgMngList(@ApiParam("招生季ID") @RequestParam("quarterId") Integer quarterId,
                                         @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                         @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId,
                                         @ApiParam("关键词") @RequestParam("keyword") String keyword,
                                         @ApiParam("查询条件") @RequestParam("condit") String condit,
                                         @ApiParam("当前页") @RequestParam("currentPage") Integer currentPage,
                                         @ApiParam("条数") @RequestParam("pageSize") Integer pageSize,
                                         @ApiParam("是否录取") @RequestParam("isAdmit") Integer isAdmit) {

            //获取当前招生季
            if(quarterId == 0){
                QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
                VeDictQuarter one = veDictQuarterService.getOne(wrapper);
                if(one==null){
                    return Result.error("列表加载失败：未启用当前招生季");
                }
                quarterId = one.getId();
            }
            if (facultyId == 0) {
                facultyId = null;
            }
            if (specialtyId == 0) {
                specialtyId = null;
            }
            if (isAdmit == 2) {
                isAdmit = null;
            }

            Integer current = (currentPage - 1) * pageSize;
            List<VeZsRegistrationVo> list = veZsRegistrationService.getApplyMsgMngList(quarterId, facultyId, specialtyId, keyword, condit, current, pageSize, isAdmit);

            //条件构造器
            QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
            wrapper.eq("isCheck",1);
            if (isAdmit != null) {
                wrapper.eq("isAdmit", isAdmit);
            }
            if (quarterId != null) {
                wrapper.eq("ZSJ", quarterId);
            }

            if (facultyId != null) {
                wrapper.eq("falId", facultyId);
            }

            if (specialtyId != null) {
                wrapper.eq("specId", specialtyId);
            }

            if (condit != null && keyword != null && (!keyword.trim().equals(""))) {
                wrapper.like(condit, keyword);
            }

            //查询总数
            Integer count = veZsRegistrationService.list(wrapper).size();

            //返回前端搜索结果
            HashMap<String, Object> map = new HashMap<>();
            map.put("list", list);
            map.put("count", count);

            return Result.OK(map);
        }



    @ApiOperation(value="批量录取")
    @RequestMapping(value = "/batchAdmit")
    public Result<?> batchReport(@ApiParam("拼接的ID字符串") @RequestParam(value = "ids") String ids){

        //切割字符串
        String[] split = ids.split(",");

        List<VeZsRegistration> list = new ArrayList<>();
        for(String sp : split){

            Long id = Long.parseLong(sp);
            VeZsRegistration veZsRegistration = new VeZsRegistration();
            veZsRegistration.setId(id);
            veZsRegistration.setIsAdmit(1);

            list.add(veZsRegistration);

        }

        veZsRegistrationService.updateBatchById(list);

        return Result.OK("批量录取成功！");

    }


    @ApiOperation(value="获取录取数量")
    @RequestMapping(value = "/getCountBySearch")
    public Result<?> getCountBySearch(@ApiParam("招生季ID") @RequestParam("quarterId") Integer quarterId,
                                      @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                      @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId){

        /*
         *当搜索条件未选择时，默认获取当前招生季
         * v2.0
         *  */
        if(quarterId == 0){
            QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
            VeDictQuarter one = veDictQuarterService.getOne(wrapper);
            quarterId = one.getId();
        }
        if(facultyId == 0){
            facultyId = null;
        }
        if(specialtyId == 0){
            specialtyId = null;
        }

        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();

        wrapper.eq("isCheck",1);

        if(quarterId != null){

            wrapper.eq("ZSJ",quarterId);
        }

        if(facultyId != null){
            wrapper.eq("falId",facultyId);
        }

        if(specialtyId != null){
            wrapper.eq("specId",specialtyId);
        }

        Integer count = veZsRegistrationService.count(wrapper);

        return Result.OK(count);
    }



    @ApiOperation(value="按条件批量录取")
    @PostMapping(value = "/batchAdmitBySearch")
    public Result<?> batchReport(@ApiParam("招生季ID") @RequestParam("quarterId") Integer quarterId,
                                 @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                 @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId){


        /*
        *当搜索条件未选择时，默认获取当前招生季
        * v2.0
        *  */
        System.out.println("前端传来的quarterId"+quarterId);
        if(quarterId == 0){
            QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
            VeDictQuarter one = veDictQuarterService.getOne(wrapper);
            quarterId = one.getId();
            System.out.println(
                   "默认招生季id"+ quarterId
            );
        }
        if(facultyId == 0){
            facultyId = null;
        }
        if(specialtyId == 0){
            specialtyId = null;
        }

        UpdateWrapper<VeZsRegistration> wrapper = new UpdateWrapper<>();

        wrapper.eq("isCheck",1);

        if(quarterId != null){
            wrapper.eq("ZSJ",quarterId);
        }

        if(facultyId != null){
            wrapper.eq("falId",facultyId);
        }

        if(specialtyId != null){
            wrapper.eq("specId",specialtyId);
        }

        wrapper.set("isAdmit",1);

        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        wrapper.set("update_time", time);

        veZsRegistrationService.update(wrapper);

        return Result.OK("按条件批量录取成功！");
    }



    //导出
    @AutoLog(value = "报名信息管理excel表格")
    @ApiOperation(value = "报名信息管理excel表格", notes = "报名信息管理—导出excel表格")
    @GetMapping(value = "/exportTable")
    // ModelAndView 导出表格流
    public ModelAndView exportTable(@ApiParam("查询条件") @RequestParam("conditions") String conditions) {
        //        ------------林彬辉
        Map<String ,Object> conditionsMap = JSONObject.parseObject(conditions);
        Integer quarterId = Integer.parseInt(conditionsMap.get("quarterId").toString());
        Long facultyId = Long.parseLong(conditionsMap.get("facultyId").toString());
        Long specialtyId = Long.parseLong(conditionsMap.get("specialtyId").toString());
        Integer isAdmitId = Integer.parseInt(conditionsMap.get("isAdmit").toString());
        //获取当前招生季
        if(quarterId == 0){
            QueryWrapper<VeDictQuarter> wrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
            VeDictQuarter one = veDictQuarterService.getOne(wrapper);
            quarterId = one.getId();
        }
        if (facultyId == 0) {
            facultyId = null;
        }
        if (specialtyId == 0) {
            specialtyId = null;
        }
        if (isAdmitId == 2) {
            isAdmitId = null;
        }
        String keyword = conditionsMap.get("keyword").toString();
        String condit = conditionsMap.get("condit").toString();
        isAdmitId = Integer.parseInt(conditionsMap.get("isAdmit").toString());
        List<ExportApplyMngVo> list = exportApplyMngService.getExportApplyMsgMngList(quarterId,facultyId,specialtyId,keyword,condit,isAdmitId);

//        List<ExportApplyMngVo> list = new ArrayList<>();


//        --------------
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得报名表表格的集合
//        List<ExportApplyMngVo> list = exportApplyMngService.getExportApplyMsgMngList();

        for (ExportApplyMngVo vo : list) {
            //数据加工处理
            String sex=vo.getXbm().equals("1")?"男":"女";
            String isAdmit=vo.getIsAdmit().equals("1")?"已录取":"未录取";
            String isReport=vo.getIsReport().equals("1")?"是":"否";

            vo.setXbm(sex);
            vo.setIsAdmit(isAdmit);
            vo.setIsReport(isReport);

        }

        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "报名信息管理");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, ExportApplyMngVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("报名信息管理", "导出人:" + user.getRealname(), "导出报名信息管理列表");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }


    /**
     *
     * 导入
     * */
    @AutoLog(value = "报名信息管理-导入excel表格")
    @ApiOperation(value = "导入excel表格", notes = "报名信息管理—导入excel表格")
    @PostMapping(value = "/importExmlByFile")
    public Result<?> excelImport(HttpServletRequest req, HttpServletResponse resp) {

        //获取当前招生季
        QueryWrapper<VeDictQuarter> wrapperA = new QueryWrapper<>();
        wrapperA.eq("isCur",1);
        //
        VeDictQuarter veDictQuarter= veDictQuarterService.getOne(wrapperA);
        if(null==veDictQuarter){
            return Result.error("导入失败，当前招生季信息有误");
        }
        //获取文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();

            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            String msg;
            try {
                // 把excel表格的数据存在集合里面去
                List<ApplyMngImportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), ApplyMngImportVo.class, params);

                for (ApplyMngImportVo applyMngImportVo : list) {
                    System.out.println("文件对象"+applyMngImportVo);

                }

                //检验必填项是否为空
                HashMap<String, String> map = veApplyMngImportService.checkList(list);
                String result=map.get("result");

                if(("0").equals(result)){
                     return Result.error(map.get("msg"));
                  }

                //林彬辉，身份证判断移动至veApplyMngImportService.checkUserful(list, veDictQuarter)内
//                int num=0;
//                for (ApplyMngImportVo vo : list) {
//                    num++;
                 //根据唯一标识  身份证号 获取对象全部信息
                    //先校验身份证格式对不对

//                  QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
//                  wrapper.eq("SFZH",vo.getSfzh());
//
//                  VeZsRegistration one = veZsRegistrationService.getOne(wrapper);
//                  if(one!=null){
//                      return Result.error("导入失败：第"+num+"行学生身份证号已存在");
//                    }
//                }
                //数据有效性校验并插入数据
                HashMap<String, String> resultMap = veApplyMngImportService.checkUserful(list, veDictQuarter);

                if(("0").equals(resultMap.get("result"))){
                    return Result.error(resultMap.get("msg"));
                }else{
                    return Result.ok(resultMap.get("msg"));

                }


            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败(类型有误/内容格式有误):" +e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");

    }



    //导出模板
    @AutoLog(value = "报名信息管理excel表格模板")
    @ApiOperation(value = "报名信息管理excel模板", notes = "报名信息管理—导出excel模板")
    @GetMapping(value = "/exportModel")
    // ModelAndView 导出表格流
    public ModelAndView exportTableModel() {
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得报名表表格的集合
        List<ApplyMngImportVo> list = new ArrayList<>();

//        for (ExportApplyMngVo vo : list) {
//            //数据加工处理
//            String sex=vo.getXbm().equals("1")?"男":"女";
//            String isAdmit=vo.getIsAdmit().equals("1")?"已录取":"未录取";
//            String isReport=vo.getIsReport().equals("1")?"是":"否";
//
//            vo.setXbm(sex);
//            vo.setIsAdmit(isAdmit);
//            vo.setIsReport(isReport);
//
//        }

        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "报名信息管理");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, ApplyMngImportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("报名信息管理", "导出人:" + user.getRealname(), "导出报名信息管理列表");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    @ApiOperation(value="获取省级列表")
    @PostMapping(value = "/getProvince")
    public Result<?> getProvince(){
        //获取区所有省级地区   pid=0
        QueryWrapper<VeDictArea> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",0);
        List<VeDictArea> list = veDictAreaService.list(wrapper);
        return Result.OK(list);
    }

    @ApiOperation(value="获取市/县级列表")
    @PostMapping(value = "/getCity")
    public Result<?> getCity(@ApiParam("上级路径ID") @RequestParam("id") Integer id){
        //获取区所有县级地区
        QueryWrapper<VeDictArea> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",id);
        List<VeDictArea> list = veDictAreaService.list(wrapper);
        return Result.OK(list);
    }

    @ApiOperation(value="获取学制列表")
    @PostMapping(value = "/getXuezi")
    public Result<?> getXuezi(){

        List<VeDictXuezi> list = veDictXueziService.list();
        return Result.OK(list);
    }


    @ApiOperation(value="获取数据字典信息")
    @PostMapping(value = "/getSysDict")
    public Result<?> getSysDict(@ApiParam("字典字段") @RequestParam("dictCode") String dictCode){

        QueryWrapper<SysDict> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dict_code",dictCode);
        SysDict sysDict = sysDictService.getOne(wrapper1);

        QueryWrapper<SysDictItem> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id",sysDict.getId());
        List<SysDictItem> list = sysDictItemService.list(wrapper);
        return Result.OK(list);

    }

    /**
     * 获取招生信息详情
     * @Author:wcj
     * 修改了数据字典，然后前端对应的axios数据处理有所调整
     * v2.0
     * 4.19
     * */
    @ApiOperation(value="获取招生信息详情（编辑）")
    @PostMapping(value = "/getInfoByID")
    public Result<?> getInfoByID(@ApiParam("id") @RequestParam("id") Long id ) {

        VeZsRegistration veZsRegistration = veZsRegistrationService.getById(id);
        return Result.OK(veZsRegistration);
    }



}

